<template>
    <div class="message-page">
        <van-nav-bar
            title="我的消息"
            fixed
            placeholder
        />
        
        <div class="message-content">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
                <van-skeleton title :row="3" :loading="loading" v-if="loading">
                    <template #template>
                        <div v-for="i in 4" :key="i" class="skeleton-item">
                            <div class="skeleton-avatar"></div>
                            <div class="skeleton-content">
                                <van-skeleton title width="40%" :row="2" />
                            </div>
                        </div>
                    </template>
                </van-skeleton>
                
                <div v-if="!loading && messageList.length === 0" class="empty-container">
                    <van-empty description="暂无消息" />
                </div>
                
                <div v-else>
                    <!-- 直接渲染消息卡片，不使用组件 -->
                    <div v-for="message in messageList" :key="message.messageId" 
                        class="message-card" @click="toMessagePage(message)">
                        <div class="avatar-container">
                            <!-- 发送者头像 -->
                            <van-image
                                class="avatar"
                                round
                                fit="cover"
                                :src="message.avatarUrl || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'"
                                alt=""
                            />
                            <div v-if="!message.isRead" class="unread-badge"></div>
                        </div>
                        <div class="message-content">
                            <div class="message-header">
                                <!-- 发送者用户名 -->
                                <div class="message-name">{{ message.userName }}</div>
                                <div class="message-time">{{ formatTime(message.sendTime) }}</div>
                            </div>
                            <div class="message-text" :class="{ 'message-text-unread': !message.isRead }">
                                {{ message.isCancel ? '[已撤回]' : message.content }}
                            </div>
                        </div>
                    </div>
                </div>
            </van-pull-refresh>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { showFailToast } from "vant";
import { getMessageList } from "../services/message";

interface Message {
    messageId: number;
    sendUserId: number;
    receiveUserId: number;
    receiveType: number;
    userName: string;
    avatarUrl: string;
    content: string;
    sendTime: string;
    isRead: number;
    isCancel: number;
    [key: string]: any;
}

interface ApiResponse {
    code: number;
    message?: string;
    data: Message[];
}

const router = useRouter();
const messageList = ref<Message[]>([]);
const loading = ref(true);
const refreshing = ref(false);

// 格式化时间为"今天 HH:MM"或"MM-DD HH:MM"格式
const formatTime = (timeStr: string): string => {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const now = new Date();
    
    // 判断是否是今天
    const isToday = date.getDate() === now.getDate() && 
                    date.getMonth() === now.getMonth() && 
                    date.getFullYear() === now.getFullYear();
    
    // 格式化小时和分钟
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const timeFormat = `${hours}:${minutes}`;
    
    if (isToday) {
        return `今天 ${timeFormat}`;
    } else {
        // 格式化月和日
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${month}-${day} ${timeFormat}`;
    }
};

// 导航到消息详情页
const toMessagePage = (message: Message) => {
    router.push({
        name: "userChat",
        params: {
            toUserId: message.receiveType === 1 ? message.receiveUserId : message.sendUserId,
            receiveType: message.receiveType.toString(),
            status: "0"
        }
    });
};

// 加载消息列表
const loadMessageList = async (): Promise<boolean> => {
    try {
        const response = await getMessageList();
        const res = response as unknown as ApiResponse;
        
        if (res.code === 0) {
            messageList.value = res.data || [];
            return true;
        } else {
            showFailToast(res.message || "获取消息失败");
            return false;
        }
    } catch (error) {
        console.error("获取消息列表失败", error);
        showFailToast("获取消息失败，请稍后重试");
        return false;
    }
};

// 下拉刷新
const onRefresh = async () => {
    try {
        await loadMessageList();
    } finally {
        refreshing.value = false;
    }
};

onMounted(async () => {
    try {
        loading.value = true;
        await loadMessageList();
    } finally {
        loading.value = false;
    }
});
</script>

<style scoped>
.message-page {
    background-color: #f7f8fa;
    min-height: 100vh;
    padding-bottom: 50px;
}

.message-content {
    padding: 8px;
}

.empty-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 70vh;
}

.skeleton-item {
    display: flex;
    background-color: #fff;
    border-radius: 15px;
    width: 96%;
    margin: 10px auto;
    padding: 12px;
    box-shadow: 1px 1px 7px rgba(0, 0, 0, 0.1);
}

.skeleton-avatar {
    width: 50px;
    height: 50px;
    margin-right: 12px;
    background-color: #f2f3f5;
    border-radius: 50%;
}

.skeleton-content {
    flex: 1;
}

/* 消息卡片样式 */
.message-card {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 12px;
    margin: 8px 0;
    padding: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.avatar-container {
    position: relative;
    margin-right: 12px;
}

.avatar {
    width: 50px;
    height: 50px;
}

.unread-badge {
    position: absolute;
    top: 0;
    right: 0;
    width: 10px;
    height: 10px;
    background-color: #ee0a24;
    border-radius: 50%;
}

.message-content {
    flex: 1;
    overflow: hidden;
}

.message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
}

.message-name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
}

.message-time {
    font-size: 12px;
    color: #999;
}

.message-text {
    font-size: 14px;
    color: #666;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    line-height: 1.5;
}

.message-text-unread {
    color: #333;
    font-weight: 500;
}
</style>
